import os
import json
import uuid
import bcrypt
import secrets
import string
import os
import logging
import hashlib
from datetime import datetime, timedelta

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('UserManager')

class UserManager:
    def __init__(self, users_file=None):
        # 默认用户数据文件路径
        if users_file is None:
            users_file = os.path.join(os.path.dirname(__file__), '../config/users.json')
        self.users_file = users_file
        
        # 确保数据目录存在
        os.makedirs(os.path.dirname(self.users_file), exist_ok=True)
        
        # 初始化用户数据
        self.users = {}
        self.load_users()
        
        # 确保有管理员账户
        self._ensure_admin_exists()
    
    def load_users(self):
        """从文件加载用户数据"""
        try:
            if os.path.exists(self.users_file):
                with open(self.users_file, 'r', encoding='utf-8') as f:
                    self.users = json.load(f)
        except Exception as e:
            print(f"加载用户数据失败: {e}")
            self.users = {}
    
    def save_users(self):
        """保存用户数据到文件"""
        try:
            with open(self.users_file, 'w', encoding='utf-8') as f:
                json.dump(self.users, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存用户数据失败: {e}")
            return False
    
    def _ensure_admin_exists(self):
        """确保管理员账户存在，如果不存在则创建"""
        if 'admin' not in self.users:
            # 生成16位强密码
            password = self.generate_strong_password(16)
            self.create_user('admin', password, 'admin')
            logger.info(f"已创建默认管理员账户 'admin'，初始密码为: {password}")
    
    def generate_strong_password(self, length=16):
        """生成强密码"""
        # 包含大小写字母、数字和特殊字符
        characters = string.ascii_letters + string.digits + string.punctuation
        # 确保密码包含至少一个小写字母、一个大写字母、一个数字和一个特殊字符
        password = [
            secrets.choice(string.ascii_lowercase),
            secrets.choice(string.ascii_uppercase),
            secrets.choice(string.digits),
            secrets.choice(string.punctuation)
        ]
        # 填充剩余字符
        password.extend(secrets.choice(characters) for _ in range(length - 4))
        # 打乱顺序
        secrets.SystemRandom().shuffle(password)
        return ''.join(password)
    
    def hash_password(self, password):
        """使用bcrypt进行密码哈希处理"""
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
    
    def verify_password(self, username, password):
        """验证密码，只使用bcrypt验证"""
        if username not in self.users:
            return False
        
        stored_hash = self.users[username]['password']
        
        # 只使用bcrypt验证
        return bcrypt.checkpw(password.encode('utf-8'), stored_hash.encode('utf-8'))
    
    def create_user(self, username, password, role='user'):
        """创建新用户"""
        if username in self.users:
            return False, "用户名已存在"
        
        # 设置默认头像路径
        default_avatar = '/static/images/favction.png'
        
        self.users[username] = {
            'username': username,
            'password': self.hash_password(password),
            'role': role,
            'created_at': datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S'),
            'last_login': None,
            'avatar': default_avatar,
            'password_reset_required': True  # 新创建的用户需要重置密码
        }
        
        if self.save_users():
            return True, "用户创建成功"
        else:
            return False, "保存用户失败"
    
    def update_user(self, username, new_password=None, new_role=None, new_avatar=None):
        """更新用户信息"""
        if username not in self.users:
            return False, "用户不存在"
        
        if new_password:
            self.users[username]['password'] = self.hash_password(new_password)
            # 密码修改后，取消重置密码的要求
            if 'password_reset_required' in self.users[username]:
                self.users[username]['password_reset_required'] = False
        
        if new_role:
            self.users[username]['role'] = new_role
            
        if new_avatar:
            self.users[username]['avatar'] = new_avatar
        
        if self.save_users():
            return True, "用户更新成功"
        else:
            return False, "保存用户失败"
    
    def delete_user(self, username):
        """删除用户"""
        if username not in self.users:
            return False, "用户不存在"
        
        if username == 'admin':
            return False, "不能删除管理员账户"
        
        del self.users[username]
        
        if self.save_users():
            return True, "用户删除成功"
        else:
            return False, "保存用户失败"
    
    def get_user(self, username):
        """获取用户信息"""
        if username not in self.users:
            return None
        
        # 返回用户信息的副本，不包含密码哈希
        user_info = self.users[username].copy()
        user_info.pop('password', None)
        return user_info
    
    def get_all_users(self):
        """获取所有用户信息"""
        result = []
        for username, user_data in self.users.items():
            user_info = user_data.copy()
            user_info.pop('password', None)
            result.append(user_info)
        return result
    
    def update_last_login(self, username):
        """更新用户最后登录时间"""
        if username in self.users:
            self.users[username]['last_login'] = datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S')
            self.save_users()
    
    def check_permission(self, username, required_permission):
        """检查用户权限"""
        if username not in self.users:
            return False
        
        role = self.users[username]['role']
        
        # 管理员拥有所有权限
        if role == 'admin':
            return True
        
        # 普通用户的权限
        if role == 'user':
            # 普通用户只允许访问首页、本地影院、本账号的用户中心
            allowed_permissions = ['index', 'local_cinema', 'user_center']
            return required_permission in allowed_permissions
        
        return False

# 创建单例实例
_user_manager = None
def get_user_manager():
    """获取用户管理器单例"""
    global _user_manager
    if _user_manager is None:
        _user_manager = UserManager()
    return _user_manager

# 测试函数（如果需要）
if __name__ == '__main__':
    um = UserManager()
    print("所有用户:", um.get_all_users())